<template>
  <div class="map-wrap">
    <div class="btns">
      <el-tooltip class="cn-btns" effect="dark"
                  content="点击，在地图上点击绘制区域，双击地图完成绘制，进入编辑状态"
                  placement="top-start">
        <el-button type="primary" @click="addRectangle()" icon="el-icon-question" size="mini">画配送区域</el-button>
      </el-tooltip>
      <el-tooltip v-if="isShowBtns" class="cn-btns" effect="dark"
                  content="点击，主动编辑已完成的区域" placement="top-start">
        <el-button type="primary" @click="eidtRectangle()" icon="el-icon-question" size="mini">编辑配送区域</el-button>
      </el-tooltip>
      <el-tooltip v-if="isShowBtns" class="cn-btns" content="点击，使编辑中的区域生效" placement="top-start">
        <el-button type="primary" @click="endEidtRectangle()" icon="el-icon-question" size="mini">结束编辑</el-button>
      </el-tooltip>
    </div>
    <div id="container" class="delivery-map" :class="{'crosshair': eidtRectanglePoint }"></div>
    <input id='searchArea' v-model="searchName" placeholder="位置模糊查询" class="input-with-select" />
  </div>
</template>
<script>
  import AMap from 'AMap'
  export default {
    props: {
      distrange: {
        type: String,
        default: ''
      },
      deliveryArea: {
        type: String,
        default: ''
      },
      agentArea: {
        type: String,
        defalut: ''
      },
      search: {
        type: String,
        defalut: ''
      }
    },
    data() {
      return {
        searchName: '',
        deliveryPolygon1: null, // 配送围栏
        agentAreaPolygonl: null, // 代理商区域
        isShowBtns: false,//显示按钮
        map: null,
        eidtRectanglePoint: false
      }
    },
    watch: {
      search(val) {
        this.searchName = val
      },
      agentArea(val) {
        this.showAgentArea(val)
      },
      deliveryArea(val) {
        this.showDeliveryArea(val)
      }
    },
    methods: {
      init: function () {  //初始化地图
        this.map = new google.maps.Map(document.getElementById('container'), {
          center: {lat: -34.397, lng: 150.644},
          mapTypeId: google.maps.MapTypeId.ROADMAP,
          zoom: 16
        });
        this.map.addListener('click', this.showInfoClick)
        var input = document.getElementById('searchArea')
        var searchBox = new google.maps.places.SearchBox(input)
        this.map.controls[google.maps.ControlPosition.TOP_LEFT].push(input)
        searchBox.addListener('places_changed', () => {
          const places = searchBox.getPlaces()
          if (places.length === 0) return
          this.map.setCenter(places[0].geometry.location)
        })
      },
      irregularPolygon(pos) { //验证是否边相交
        const lines = [] //多边形的所有边
        for (var i = 0; i < pos.length; i++) {
          if (i < pos.length - 1) {
            lines.push([pos[i], pos[i + 1]])
          } else {
            //最后要给点连第一个点
            lines.push([pos[i], pos[0]])
          }
        }
        //其中一个变和所有边里判断 n*n循环
        let whetherTheIntersection = false
        lines.forEach((item, index1) => {
          lines.forEach((list, index2) => {
            //自己和自己不比较 ，也不和相邻的比较
            const comparison = () => {
              let ml = lines.length - 1
              if (index1 == index2) return false
              else {
                if (index1 == 0) {
                  if (index2 == 1 || index2 == ml) return false
                } else if (index1 == ml) {
                  if (index2 == 0 || index2 == (ml - 1)) return false
                } else {
                  if (index2 == 0) {
                    if (index1 == 1 || index1 == ml) return false
                  } else if (index2 == ml) {
                    if (index1 == ml - 1) return false
                  } else {
                    if (index1 == (index2 + 1) || (index1 == index2 - 1)) return false
                  }
                }
              }
              return true
            }
            if (comparison()) {
              let p1 = item[0], p2 = item[1], p3 = list[0], p4 = list[1]
              let isPointInRing = AMap.GeometryUtil.doesSegmentsIntersect(p1, p2, p3, p4)
              if (isPointInRing) {
                whetherTheIntersection = true
                return false
              }
            }
          })
        })
        return whetherTheIntersection
      },
      eidtRectangle() { //编辑多边形
        if (this.deliveryPolygon1) {
          this.deliveryPolygon1.setEditable(true)
        }
      },
      endEidtRectangle() { //结束画多边形
        if (this.deliveryPolygon1) {
          const array = this.deliveryPolygon1.getPath().getArray()
          const arr = []
          const arrForInPolygon = []
          array.forEach(item => {
            arr.push(`${item.lng()},${item.lat()}`)
            arrForInPolygon.push([item.lng(), item.lat()])
          })
          if (!this.irregularPolygon(arrForInPolygon)) {
            this.deliveryPolygon1.setEditable(false)
            this.$emit('surDistrange', arr.join('|') + '|')
          } else {
            this.eidtRectangle()
            this.$alert('请绘制有规则的多边形（多边形任意边不相错）')
          }
        }
      },
      addRectangle() {  //画多边形
        this.eidtRectanglePoint = true
        if (this.deliveryPolygon1) {
          this.deliveryPolygon1.setMap(null)
          this.deliveryPolygon1 = null
        }
        this.isShowBtns = false
        const mouseTool = new google.maps.drawing.DrawingManager({
          drawingMode:google.maps.drawing.OverlayType.POLYGON,
          drawingControl: false,
          polygonOptions: {
            strokeColor: "#3c48f5",
            strokeOpacity: 1,
            strokeWeight: 2,
            fillColor: '#448ef5',
            fillOpacity: 0.35,
            clickable: false,
            editable: true,
            zIndex: 1
          }
        })
        mouseTool.setMap(this.map)  //繪圖工具加載設置
        google.maps.event.addListener(mouseTool, 'polygoncomplete', polygon => { // 退出繪圖模式
          mouseTool.setDrawingMode(null)
          this.isShowBtns = true
          this.deliveryPolygon1 = polygon
          this.eidtRectanglePoint = false
        })
      },
      searlDistrange(pos) { // 过滤后台存储的经纬度
        let position = pos.trim()
        let lastStr = position.charAt(position.length - 1)
        if (lastStr == '|') {
          position = position.substring(0, position.lastIndexOf('|'))
        }
        let positionArr = []
        position.split('|').forEach(item => {
          const pos = item.split(',')
          positionArr.push({lng: parseFloat(pos[0]), lat: parseFloat(pos[1])})
        })
        return positionArr
      },
      setFitView(positionArr) { // 围栏自适应在地图上
        const bounds = new google.maps.LatLngBounds()
        positionArr.forEach(item => {
          bounds.extend(item)
        })
        this.map.fitBounds(bounds)
      },
      showDeliveryArea(pos) { // 显示代理商配送区域
        if (this.deliveryPolygon1) {
          this.deliveryPolygon1.setMap(null)
          this.deliveryPolygon1 = null
        }
        this.deliveryPolygon1 = new google.maps.Polygon({
          paths: this.searlDistrange(pos),
          strokeColor: "#3c48f5",
          strokeOpacity: 1,
          strokeWeight: 2,
          fillColor: "#448ef5",
          fillOpacity: 0.35
        })
        this.isShowBtns = true
        this.deliveryPolygon1.setMap(this.map)
        this.setFitView(this.searlDistrange(pos))
      },
      showAgentArea(pos) { // 显示代理商区域
        if (this.agentAreaPolygon1) {
          this.agentAreaPolygon1.setMap(null)
          this.agentAreaPolygon1 = null
        }
        this.agentAreaPolygon1 = new google.maps.Polygon({
          paths: this.searlDistrange(pos),
          strokeColor: "#ff232f",
          strokeOpacity: 1,
          strokeWeight: 2,
          fillColor: "#6bf517",
          fillOpacity: 0.35
        })
        this.agentAreaPolygon1.setMap(this.map)
        this.setFitView(this.searlDistrange(pos))
      }
    },
    mounted() {
      this.init()
      // google.maps.event.addDomListener(window, 'load', this.init())
    }
  }
</script>
<style lang="scss">
  #searchArea {
    position: absolute !important;
    right: 10px !important;
    top: 10px !important;
    left: auto !important;
    background-color: #fff;
    font-size: 15px;
    font-weight: 300;
    height: 20px;
    line-height: 20px;
    padding: 5px;
    text-overflow: ellipsis;
    width: 300px;
  }
  #searchArea:focus {
    border-color: #4d90fe;
  }
</style>
<style lang="scss" scoped>
  .map-wrap{
    position: relative;
    width: 100%;
    .btns{
      position: absolute;
      z-index: 9;
      left: 10px;
      top: 10px;
      height: 40px;
    }
    .delivery-map{
      width: 100%;
      height: 100%;
      &.crosshair{
        cursor: crosshair;
      }
    }
  }
</style>
